package com.taxshare.manager.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.manager.constant.ResultConstant;
import com.taxshare.manager.entity.OrganizeEntity;
import com.taxshare.manager.entity.UserOrganizeEntity;
import com.taxshare.manager.mapper.UserOrganizeMapper;
import com.taxshare.manager.view.dto.UserOrgDTO;
import com.taxshare.manager.view.vo.CompanyVO;
import com.taxshare.manager.view.vo.OrganizeVO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.constant.CommonConstant;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: UserOrgService
 * @Description:
 * @author: luozhongyi
 * @date: 2021/2/4 14:34
 */
@Service
public class UserOrgService extends ServiceImpl<UserOrganizeMapper, UserOrganizeEntity> {

    /**
     * 保存关联税号
     *
     * @param userOrgDTO
     * @return
     */
    public Response saveTaxNumbers(UserOrgDTO userOrgDTO) {
        if (ArrayUtil.hasEmpty(userOrgDTO.getOrgIds())) {
            return Response.error(ResultConstant.RET_U0003_CODE, ResultConstant.RET_U0003_MSG);
        }
        //先删除
        QueryWrapper<UserOrganizeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userOrgDTO.getUserId());
        this.remove(queryWrapper);
        List<UserOrganizeEntity> userOrganizeEntities = new ArrayList<>();
        UserOrganizeEntity userOrganizeEntity;
        for (String orgId : userOrgDTO.getOrgIds()) {
            userOrganizeEntity = new UserOrganizeEntity();
            userOrganizeEntity.setUuid(UUIDUitl.UUID32(false));
            userOrganizeEntity.setUserId(userOrgDTO.getUserId());
            userOrganizeEntity.setOrgId(orgId);
            userOrganizeEntities.add(userOrganizeEntity);
        }
        baseMapper.insertUserOrgBatch(userOrganizeEntities);
        return Response.success();
    }

    /**
     * 初始化用户关联的组织列表
     *
     * @param
     * @return
     */
    public Response initLoginUserOrgs() {
        List<String> companyEntities = null;
        String userType = UserInfoUtil.getUserType();
        QueryWrapper<UserOrganizeEntity> queryWrapper = new QueryWrapper();
        //普通用户根据用户id查询
        if (CommonConstant.AUTH_TYPE_1.equals(userType) || CommonConstant.AUTH_TYPE_2.equals(userType)) {
            queryWrapper.eq("t.user_id", UserInfoUtil.getUserID());
            companyEntities = baseMapper.initLoginUserOrgs(queryWrapper);
        } else {
            //管理员查询全部
            companyEntities = baseMapper.initTenantOrgs().stream().map(t -> t.getOrgId()).collect(Collectors.toList());
        }
        return Response.success(companyEntities);
    }


    /**
     * 初始化组织税号列表
     *
     * @param
     * @return
     */
    public Response initLoginUseTaxNos() {
        String userType = UserInfoUtil.getUserType();
        List<CompanyVO> companyEntities = null;
        //普通用户
        if (CommonConstant.AUTH_TYPE_1.equals(userType) || CommonConstant.AUTH_TYPE_2.equals(userType)) {
            QueryWrapper<UserOrganizeEntity> queryWrapper = new QueryWrapper();
            queryWrapper.eq("t.user_id", UserInfoUtil.getUserID());
            companyEntities = baseMapper.initLoginUserTaxNos(queryWrapper);
        } else if (CommonConstant.AUTH_TYPE_3.equals(userType)) {
            companyEntities = baseMapper.initAllTaxNos();
        }
        return Response.success(companyEntities);
    }

    /**
     * 用户已经绑定的税号
     *
     * @param userOrgDTO
     * @return
     */
    public Response getOrgs(UserOrgDTO userOrgDTO) {
        QueryWrapper<UserOrganizeEntity> queryWrapper = new QueryWrapper();
        if (StrUtil.hasBlank(userOrgDTO.getUserId())) {
            return Response.error(ResultConstant.RET_U0004_CODE, ResultConstant.RET_U0004_MSG);
        } else {
            queryWrapper.eq("t.user_id", userOrgDTO.getUserId());
        }
        List<String> orgs = baseMapper.initLoginUserOrgs(queryWrapper);
        return Response.success(orgs);
    }


    /**
     * 初始化当前登录用户不能操作的组织列表
     *
     * @param
     * @return
     */
    public Response userAuthOrg(String userId) {
        //用户不能操作的组织
        List<String> userUnableOrgs = initLoginUserUnableOrgs();
        //当前登录用户所有组织权限
        List<OrganizeEntity> organizeEntities = baseMapper.initTenantOrgs();
        if (CollectionUtils.isEmpty(organizeEntities)) {
            return Response.success(organizeEntities);
        }
        List<OrganizeVO> resourceVOList = JSONUtil.toList(JSONUtil.parseArray(organizeEntities), OrganizeVO.class);
        //构造菜单树
        Map<String, OrganizeVO> dataMap = new HashMap<>(resourceVOList.size() * 4 / 3 + 1);
        for (OrganizeVO bean : resourceVOList) {
            dataMap.put(bean.getOrgId(), bean);
        }
        //构造Tree
        List<OrganizeVO> treeList = new ArrayList<>(30);
        for (OrganizeVO bean : resourceVOList) {
            //如果父节点为0,则表示其为根节点
            if ("0".equals(bean.getOrgPid())) {
                treeList.add(bean);
            } else {
                //获取父节点所在的对象
                OrganizeVO parentEntity = dataMap.get(bean.getOrgPid());
                //如果为null则表明此节点的父节点不存在了
                if (parentEntity != null) {
                    //将其存放到父节点的children属性下
                    parentEntity.getChildren().add(bean);
                }
                //如果用户不能有这个属性就禁用
                for (String orgId : userUnableOrgs) {
                    if (orgId.equals(bean.getOrgId())) {
                        bean.setDisabled(Boolean.TRUE);
                    }
                }
            }
        }
        return Response.success(treeList);
    }

    /**
     * 获取用户的的组织权限
     *
     * @return
     */
    public List<String> initLoginUserUnableOrgs() {
        String userType = UserInfoUtil.getUserType();
        Map<String, String> queryWrapper = new HashMap<>(8);
        List<String> userUnableOrgs = null;
        if (CommonConstant.AUTH_TYPE_1.equals(userType)) {
            queryWrapper.put("user_id", UserInfoUtil.getUserID());
            userUnableOrgs = baseMapper.initLoginUserUnableOrgs(queryWrapper);
        } else if (CommonConstant.AUTH_TYPE_2.equals(userType) || CommonConstant.AUTH_TYPE_3.equals(userType)) {
            userUnableOrgs = new ArrayList<>();
        }
        return userUnableOrgs;
    }
}
